package com.bt.att;

import com.bt.att.dao.GBHelper;
import com.bt.att.dao.PhoneDao;
import com.bt.att.model.*;
import org.jfree.chart.*;
import org.jfree.chart.entity.CategoryItemEntity;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
import org.springframework.beans.factory.annotation.Autowired;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;

public class ChartJPanel extends JPanel implements ActionListener, ChartMouseListener {
    private static final String CALL = "Calls";
    private static final String MESSAGE = "Messages";
    private static final String[] chartTypeNames = new String[] {"Number of calls by person",
            "Call duration by person", "Number of Texts by Person", "Number of calls by time",
            "Call duration by time", "Number of Texts by time"};

    private static final int BORDER = 12;  // Window border in pixels.
    private static final int GAP    = 5;   // Default gap btwn components.
    private int axis;
    private Map<String, Phone> nameToPhones = new HashMap<String, Phone>();
    private JComboBox comboBoxName;
    private JComboBox comboBoxChartTypes;
    private JRadioButton callButton;
    private JRadioButton messageButton;
    private ChartPanel panel;
    private JFreeChart chart;

    @Autowired
    private ChartDataReader reader;

    @Autowired
    private PhoneDao dao;

    @Autowired
    private DetailsTablePane table;

    public void setAxis(int axis) {
        this.axis = axis;
    }

    public void init() {
        setPreferredSize(new Dimension(800, 600));
        setLayout(new GridBagLayout());
        GBHelper pos = new GBHelper();

        List<Phone> phones = dao.getFamilyPhones();
        nameToPhones.clear();
        List<String> list = new ArrayList<String>();
        for (Phone phone : phones) {
            list.add(phone.getPerson());
            nameToPhones.put(phone.getPerson(), phone);
        }

        comboBoxName = new JComboBox(list.toArray(new String[0]));
        if (list.size() > 0) {
            comboBoxName.setSelectedIndex(0);
        }
        comboBoxName.addActionListener(this);
        add(comboBoxName, pos);
        add(new Gap(GAP), pos.nextCol());
        comboBoxChartTypes = new JComboBox(ChartType.chartTypeMap().keySet().toArray(new String[0]));
        comboBoxChartTypes.setSelectedIndex(0);
        comboBoxChartTypes.addActionListener(this);
        add(comboBoxChartTypes, pos.nextCol());
        add(new Gap(GAP), pos.nextCol());


        JButton refreshButton = new JButton("Refresh");
        refreshButton.addActionListener(this);
         add(refreshButton, pos.nextCol());

        chart = createChart();

        panel = new ChartPanel(chart);
        ChartData chartData = new ChartData();
        chartData.setTitle("Test");
        chartData.setAxisTitle("AxisTitle");
        add(panel, pos.nextRow().expandH());
        panel.addChartMouseListener(this);

//        table = new DetailsTablePane();
//        table.init();
        add(table, pos.nextCol().width().expandH());
    }

    private JFreeChart createChart() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        JFreeChart chart = ChartFactory.createBarChart("Test", "Number", "Marks", dataset,
            PlotOrientation.HORIZONTAL, false,true, false);
//        chart.setBackgroundPaint(Color.yellow);
//        chart.getTitle().setPaint(Color.blue);
        return chart;
    }

    private void refreshChartData() {
        String person = comboBoxName.getSelectedItem().toString();
        Phone phone = nameToPhones.get(person);
//       boolean isCall = true;
//        if (messageButton.isSelected()) {
//            isCall = false;
//        }
        String type = comboBoxChartTypes.getSelectedItem().toString();
        ChartType chartType = ChartType.fromString(type);
        ChartData chartData = reader.getChartData(chartType, phone.getNumber(), null, null);
        createAndSetChart(chartData);
    }

    public void createAndSetChart(ChartData chartData) {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        String axisTitle = "";
        for (ChartSeries series : chartData.getSeries()) {
            axisTitle = series.getSeriesName();
            for (ChartPoint point : series.getPoints()) {
                dataset.setValue(point.getValue(), series.getAxisTitle(), point.getName().toString());
            }
        }

        chart.setTitle(chartData.getTitle());
        chart.getCategoryPlot().setDataset(dataset);
        chart.getCategoryPlot().getDomainAxis().setLabel(chartData.getAxisTitle());
        chart.getCategoryPlot().getRangeAxis().setLabel(axisTitle);
//        JFreeChart chart = ChartFactory.createBarChart(chartData.getTitle(), "Number", "Marks", dataset,
//            PlotOrientation.HORIZONTAL, false,true, false);
//        chart.setBackgroundPaint(Color.yellow);
//        chart.getTitle().setPaint(Color.blue);
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        refreshChartData();
    }

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    }

    @Override
    public void chartMouseClicked(ChartMouseEvent event) {
        if (event.getEntity() instanceof CategoryItemEntity) {
            CategoryItemEntity entity = (CategoryItemEntity) event.getEntity();
            String rowKey = entity.getRowKey().toString();
            String columnKey = entity.getColumnKey().toString();
            String person = comboBoxName.getSelectedItem().toString();
            Phone phone = nameToPhones.get(person);
            String domainAxisLabel = chart.getCategoryPlot().getDomainAxis().getLabel().toLowerCase();
            if ("number".equals(domainAxisLabel)) {
                String toNumber = columnKey.split(" ")[0];
                if (rowKey.toLowerCase().contains("calls")) {
                    List<Call> calls = dao.getCalls(phone.getNumber(), toNumber, null, null);
                    table.setCalls(calls);
                } else {
                    List<Message> messages = dao.getMessages(phone.getNumber(), toNumber, null, null);
                    table.setMessages(messages);
                }
            } else if ("hour".equals(domainAxisLabel)) {
                String hourStr = columnKey.split(":")[0];
                int hour = Integer.parseInt(hourStr);
                if (rowKey.toLowerCase().contains("calls")) {
                    List<Call> calls = dao.getCalls(phone.getNumber(), hour, null, null);
                    table.setCalls(calls);
                } else {
                    List<Message> messages = dao.getMessages(phone.getNumber(), hour, null, null);
                    table.setMessages(messages);
                }

            }
            int ii = 0;

        }
    }

    @Override
    public void chartMouseMoved(ChartMouseEvent chartMouseEvent) {
        //To change body of implemented methods use File | Settings | File Templates.
    }








}